<?php
session_start();
include 'comm/config.php';
include_once 'comm/Taoapi.php';
include 'data/expression.php';
include_once 'comm/checkpostandget.php';
$shai_set=include 'data/shai.php';
$patterns = include ('cache/no_words.php');

function check_content($arr){ //数组加addslashes
	foreach ($arr as $key => $value) {
        if (is_array($value)) {
            check_content($arr[$key]);
        } else {
            $value = trim($value);
            if(get_magic_quotes_gpc()==0){
		        $arr[$key] = addslashes($value);
	        }
        }
    }
	return $arr;
}

if($_POST['fun']=='save_shai' || $_POST['fun']=='save_share' || $_POST['fun']=='save_comment'){
    $replacements = '';  //输出模式替换结果
    $_POST['comment']=str_replace($patterns, $replacements, $_POST['comment']);
	$_POST['keywords']=str_replace($patterns, $replacements, $_POST['keywords']);
}

function insert_one_sql($table, $field_arr, $alert = 0) {
	global $BIAOTOU;
	$field = "";
	$values = "";
	foreach ($field_arr as $k => $v) {
		$field = "`" . $k . "`," . $field;
		$values = "'" . $v . "'," . $values;
	}
	$field = substr($field, 0, strlen($field) - 1);
	$values = substr($values, 0, strlen($values) - 1);
	$sql = "insert into $BIAOTOU$table($field) values ($values);";
	$query = mysql_query($sql);
	if ($alert == 0) {
		if ($query)
			return mysql_insert_id();
		else
			return mysql_error();
	}
	elseif ($alert == 1) {
		echo $sql;
	}
	elseif ($alert == 2) {
		echo $sql;
		if ($query)
			return 1;
		else
			return mysql_error();
	}
}

function sel_sql($table,$sel_field,$where,$alert=0){
	global $BIAOTOU;
	$sql="select $sel_field from $BIAOTOU$table where $where";
	if($alert==1){
	    echo $sql;
	}
	$query=mysql_query($sql);
	if($query){
		while($row=mysql_fetch_array($query)){
			if(strpos($sel_field,",") or $sel_field=="*"){
			    $arr=$row;
			}
			else{
			    $arr=$row[$sel_field];
			}
		}
	}
	return $arr;	
}

function update_sql($table,$field_arr,$where,$xs,$alert=0){ //$xs 0表示更新 1表示同加  2表示同减,$alert默认为0,1表示打印sql语句,2表示先执行在打印
    global $BIAOTOU;
	$sql="";
	foreach($field_arr as $k=>$v){
		if($xs==0){
		    $sql="`$k`='$v',".$sql;
		}
		elseif($xs==1){
		    $sql="`$k`=`$k`+'$v',".$sql;
		}
		elseif($xs==2){
		    $sql="`$k`=`$k`-'$v',".$sql;
		}
	}
	$sql=substr($sql,0,strlen($sql)-1);
	$sql="update $BIAOTOU$table set $sql where $where;";
	if($alert==0){
		mysql_query($sql);
	}
	elseif($alert==1){
		echo $sql;
	}
	elseif($alert==2){
		mysql_query($sql);
	    echo $sql; 
	}
}

function over($word){
    mysql_close();
	echo $word;
	exit;
}

function tao_item_cat($cid){
	$Taoapi_Config = Taoapi_Config::Init();
    $Taoapi_Config->setCharset('UTF-8');
    $Taoapi = new Taoapi;
	$Taoapi->nick = MYUSERNICK;
    $Taoapi->method = 'taobao.itemcats.get';
    $Taoapi->cids = $cid;
    $Taoapi->fields = 'parent_cid';
    $TaobaokeData = $Taoapi->Send('get','xml')->getArrayData();
	//print_r($TaobaokeData);
	$parent_cid=$TaobaokeData['item_cats']['item_cat']['parent_cid'];
	global $shai_cat_id_temp;
	$shai_cat_id_temp=in_tao_cat($parent_cid);
	if($shai_cat_id!=999){
		return false;
	}
	else{
	    tao_item_cat($parent_cid);
	}
}

function in_tao_cat($cid){
	$tao_cat=include('data/tao_cat.php');
    foreach($tao_cat as $k=>$v){
	    if(in_array($cid,$v)){
		    return $k;
	    }
    }
	return 999;
}

function mingxi_msg($name,$jifen,$username=''){
	if($username==''){$username=$_SESSION['duoduouser'];}
    //用户消息
	$title = '您获得了新的'.$name.'积分！';
	$msg = '您获得了新的'.$name.'积分'.$jifen;
	$filed_arr = array (
	    'title' => $title,
		'content' => $msg,
		'addtime' => date('Y-m-d H:i:s'), 
		'see' => 0, 
		'ddusername' => $username, 
		'senduser' => '网站客服'
	);
	insert_one_sql("msg", $filed_arr);

	//用户明细
	$shijian = $name.'积分';
	$memo = $name.'积分'.$jifen;
	$filed_arr = array (
		'ddusername' => $username,
		'shijian' => $shijian,
		'addtime' => date('Y-m-d H:i:s'), 
		'je' => 0, 
		'jifen'=>$jifen,
		'memo' => $memo
	);
	insert_one_sql("mingxi", $filed_arr);
}

$iid_arr = array (
	'id',
	'item_num_id',
	'default_item_id',
	'item_id',
	'itemId',
	'mallstItemId'
);

function get_tao_id_key($a, $iid_arr) {
	$c=count($iid_arr);
	for ($i = 0; $i < $c; $i++) {
		if (array_key_exists($iid_arr[$i], $a)) {
			if ($a[$iid_arr[$i]] != '') {
				return $a[$iid_arr[$i]];
			}
		}
	}
}

function get_fan($title,$nick,$p){
	$Taoapi = new Taoapi;
    $Taoapi->method = 'taobao.taobaoke.items.get';
    $Taoapi->fields = 'title,nick,price,click_url,shop_click_url,commission';
    $Taoapi->nick = MYUSERNICK;
    $Taoapi->keyword=$title;
    $Taoapi->page_size=20;
	$Taoapi->sort='commissionNum_desc';
    $Taoapi->outer_code = $_SESSION['dduserid'];
    $TaobaokeData = $Taoapi->Send('get','xml')->getArrayData();
	$arr=$TaobaokeData['taobaoke_items']['taobaoke_item'];
	if($arr[0]=='') $row[0]=$arr;
	else $row=$arr;
	for($i=0;$i<count($row);$i++){
	    if($row[$i]['nick']==$nick && strip_tags($row[$i]['title'])==$title){
		    $re=$row[$i];
			$i=9999999;
		}
	}
	if($p=='commission') return $re['commission'];
	if($p=='click_url') return $re['click_url'];
}

if($_POST['fun']=='get_tao_img' && $_POST['url']!=''){
	$b=explode('?',$_POST['url']);
	parse_str($b[1],$a);
	$iid=get_tao_id_key($a, $iid_arr);
	$Taoapi_Config = Taoapi_Config::Init();
    $Taoapi_Config->setCharset('UTF-8');
    $Taoapi = new Taoapi;
	
	$Taoapi->nick = MYUSERNICK;
	$Taoapi->method = 'taobao.taobaoke.items.detail.get';
    $Taoapi->fields = 'title,cid,pic_url,price,click_url,nick';
    $Taoapi->num_iids = $iid;
	$TaobaokeData = $Taoapi->Send('get','xml')->getArrayData();
	$row=$TaobaokeData['taobaoke_item_details']['taobaoke_item_detail']['item'];
	$cid=$row['cid'];
	$img=$row['pic_url'].'_310x310.jpg';
	$title=$row['title'];
	$price=$row['price'];
	$nick=$row['nick'];
	$click_url=$TaobaokeData['taobaoke_item_details']['taobaoke_item_detail']['click_url'];
	$shai_cat_id=in_tao_cat($cid);
	if($shai_cat_id==999){
	    tao_item_cat($cid);
	    $shai_cat_id=$shai_cat_id_temp;
	}
	
	if($_POST['xs']=='shai'){
	    $json_arr=array('img'=>$img,'cid'=>$shai_cat_id,'clickUrl'=>$click_url);
	}
	elseif($_POST['xs']=='share'){
	    $json_arr=array('img'=>$img,'cid'=>$shai_cat_id,'clickUrl'=>$click_url,'title'=>$title,'price'=>$price,'nick'=>$nick);
	}
	if($shai_set['re_tao_cid']==1 && $shai_cat_id==999){
		file_put_contents('data/tao_cid.txt',$_POST['url'].'|||'.$cid."\r\n",FILE_APPEND);
	}
	echo json_encode($json_arr);
}

if($_POST['fun']=='save_shai'){
	$keywords_arr = preg_split('/[\n\r\t\s]+/i', trim($_POST['keywords']));
	$image=$_POST['image'];
	//$temp=preg_replace('/\{.*?\}/im','',$_POST['comment']);
	if(count($keywords_arr)>5){
	    $json_arr=array('err'=>1,'msg'=>1);
	}
	elseif($image=='' || $image=='../images/wait.gif' || $image=='null'  || tao_img=='_310x310.jpg'  || tao_img=='../images/crying.gif'){
	    $json_arr=array('err'=>1,'msg'=>9);
	}
	elseif($_POST['comment']==''){
	    $json_arr=array('err'=>1,'msg'=>8);
	}
	else{
		$field_arr=array_diff($_POST, array('fun'=>'save_shai'));
		$field_arr['ddusername']=$_SESSION['duoduouser'];
		$field_arr['dduserid']=$_SESSION['dduserid'];
		$field_arr['xs']='shai';
		$field_arr['time']=time();
		$field_arr['tao_id']=(float)$field_arr['tao_id'];
		$black_tao_id=sel_sql('shai_blacklist','tao_id',"tao_id='".$field_arr['tao_id']."'",0);
	    $id=sel_sql('shai','id',"trade_id='".$field_arr['trade_id']."'",0);
		$id2=sel_sql('shai','id',"tao_id='".$field_arr['tao_id']."' and dduserid='".$_SESSION['dduserid']."'",0);
		
		if($id>0){
		    $json_arr=array('err'=>1,'msg'=>5);
		}
		elseif($id2>0){
		    $json_arr=array('err'=>1,'msg'=>5);
		}
		elseif($black_tao_id>0){
		    $json_arr=array('err'=>1,'msg'=>15);
		}
		
		else{
			$field_arr['jifen']=$shai_set['shai_jifen'];
			$id=insert_one_sql('shai', $field_arr,0);
		    unset($field_arr);
		    if($shai_set['shai_jifen']>0){
			    $jifen=$shai_set['shai_jifen'];
		        $field_arr=array('jifen'=>$jifen);
		        update_sql('user',$field_arr,'Id="'.$_SESSION['dduserid'].'"',1,0);
				mingxi_msg('晒单',$jifen);
		    }
	        if(intval($id)<0){
	            $json_arr=array('err'=>1,'msg'=>3);
	        }
		    else{
		        $json_arr=array('err'=>0,'msg'=>4);
		    }
		}
	}
	echo json_encode($json_arr); 
}

if($_POST['fun']=='save_share'){
	$keywords_arr = preg_split('/[\n\r\t\s]+/i', trim($_POST['keywords']));
	$title=$_POST['title'];
	$a=explode('&ref=',$_POST['url']);
	$url=$a[0];
	$_POST['url']=$url;
	$price=$_POST['price'];
	$image=$_POST['image'];
	$catid=(int)$_POST['catid'];
	$nick=$_POST['nick'];
	unset($_POST['nick']);
	//$temp=preg_replace('/\{.*?\}/im','',$_POST['comment']);
	
	if($_SESSION["dduserlevel"]<$shai_set['limit_level']){
	    $json_arr=array('err'=>1,'msg'=>6);
	}
	elseif(count($keywords_arr)>5){
	    $json_arr=array('err'=>1,'msg'=>1);
	}
	elseif($title=='' || $url=='' || $price=='' || $catid==''){
	    $json_arr=array('err'=>1,'msg'=>7);
	}
	elseif($image=='' || $image=='images/wait.gif' || $image=='null' || image=='_310x310.jpg' || image=='../images/crying.gif'){
	    $json_arr=array('err'=>1,'msg'=>9);
	}
	elseif($_POST['comment']==''){
	    $json_arr=array('err'=>1,'msg'=>8);
	}
	else{
		$b=explode('?',$_POST['url']);
	    parse_str($b[1],$a);
	    $iid=get_tao_id_key($a, $iid_arr);
		$field_arr=array_diff($_POST, array('fun'=>'save_share'));
		$field_arr['tao_id']=$iid;
		$field_arr['ddusername']=$_SESSION['duoduouser'];
		$field_arr['dduserid']=$_SESSION['dduserid'];
		$field_arr['xs']='share';
		$field_arr['time']=time();
		
		$Taoapi_Config = Taoapi_Config::Init();
        $Taoapi_Config->setCharset('UTF-8');
        $Taoapi = new Taoapi;
		$Taoapi->method = 'taobao.taobaoke.items.convert';
        $Taoapi->fields = 'commission';
        $Taoapi->nick =  MYUSERNICK;
        $Taoapi->num_iids=$iid;
        $CommData = $Taoapi->Send('get','xml')->getArrayData();

        if(empty($CommData)){
		    $commission=get_fan($title,$nick,'commission');
		}
		else{
		    $commission=$CommData['taobaoke_items']['taobaoke_item']['commission'];
		}
		
        $ThisComm=ck_fxje($commission,0);
        if($ThisComm>0){
			$field_arr['fxje']=$ThisComm;
        }
		else{
			$field_arr['fxje']=0;
		}

		$id=sel_sql('shai','id',"tao_id='".$field_arr['tao_id']."' and dduserid='".$_SESSION['dduserid']."'",0);
		$black_tao_id=sel_sql('shai_blacklist','tao_id',"tao_id='".$field_arr['tao_id']."'",0);
		if($id>0){
		    $json_arr=array('err'=>1,'msg'=>5);
		}
		elseif($black_tao_id>0){
		    $json_arr=array('err'=>1,'msg'=>15);
		}
		else{
			$field_arr['jifen']=$shai_set['share_jifen'];
		    $id=insert_one_sql('shai', $field_arr,0);
	        if($id<1){
	            $json_arr=array('err'=>1,'msg'=>mysql_error());
	        }
		    else{
				if($shai_set['share_jifen']>0){
					unset($field_arr);
				    $field_arr['jifen']=$shai_set['share_jifen'];
					update_sql('user',$field_arr,'Id="'.$_SESSION['dduserid'].'"',1,0);
					mingxi_msg('分享',$shai_set['share_jifen']);
			    }
		        $json_arr=array('err'=>0,'msg'=>4);
		    }
		}  
	}
	echo json_encode($json_arr); 
}

if($_POST['fun']=='inc_hart'){
    $info['shai_id']=$_POST['shai_id'];
	$info['xs']=$_POST['xs'];
	$info['dduserid']=$_SESSION['dduserid'];
	$info['time']=time();
	if($_SESSION['dduserid']<=0){
	    $json_arr=array('err'=>1,'msg'=>7);
	}
	else{
	    $id=sel_sql('shai_hart','id','shai_id="'.$_POST['shai_id'].'" and dduserid="'.$_SESSION['dduserid'].'"');
	    if($id>0){
	        $json_arr=array('err'=>1,'msg'=>6);
	    }
	    else{
	        $sql="update ".$BIAOTOU."shai set hart=hart+1 where id='".$_POST['shai_id']."' limit 1";
	        mysql_query($sql);
			$sql="select a.ddusername,b.dduserid from ".$BIAOTOU."user as a,".$BIAOTOU."shai as b where b.id='".$_POST['shai_id']."' and a.Id=b.dduserid";
			$query=mysql_query($sql);
			$row=mysql_fetch_array($query);
			$shai_user_id=$row['dduserid'];
			$shai_user_name=$row['ddusername'];
			$field_arr=array('hart'=>1);
			if($shai_set['hart_jifen']>0 && $shai_user_name!=''){
			    $jifen=$shai_set['hart_jifen'];
				$field_arr['jifen']=$jifen;
				mingxi_msg('红心',$jifen,$shai_user_name);
			}
			update_sql('user',$field_arr,'Id='.$shai_user_id,1,0);
	        $id=insert_one_sql('shai_hart', $info);
		    $json_arr=array('err'=>0,'msg'=>4);
	    }
	}
	echo json_encode($json_arr);
}

if($_POST['fun']=='save_comment'){
	$time=sel_sql('shai_comment','time',"dduserid=".$_SESSION['dduserid'],0);
	if(time()-$time<10){
	    over(8);
	}
	if($_SESSION["dduserlevel"]<$shai_set['limit_level'] || $_SESSION['duoduouser']==''){
	    over(9);
	}
	if($_POST['comment']==''){
	    over(12);
	}
    $info['shai_id']=$_POST['shai_id'];
	$info['comment']=$_POST['comment'];
	$info['dduserid']=$_SESSION['dduserid'];
	$info['ddusername']=$_SESSION['duoduouser'];
	$info['time']=time();
	$id=insert_one_sql('shai_comment', $info,0);
	if(intval($id)>0){?>
	    <li class="show" style="display:none">
              <div class="avatar"><a href="userbao.php?id=<?=$_SESSION['dduserid']?>"><img onerror="this.src='images/noavatar_small.gif'" src="upload/avatar/<?=get_avatar_filepath($_SESSION['dduserid'], $size = 'small', $type = '')?>" /></a></div>
              <div class="more">
                <div style="margin-bottom:0px"><span style="color:#FF6699"><?=$_SESSION['duoduouser']?></span><span class="time"><?=date('m月d日 H:i')?></span></div>
                <div class="words">
				<?php
				foreach($expression as $k=>$v){
                    $info['comment'] = str_replace('{' .$v. '}','<img src="images/emoticons/' . $k . '.gif"/>',$info['comment']); 
                }
                echo $info['comment'];
				?>
                </div>
              </div>
              <div style="height:6px; clear:both"></div>
            </li>
<?php }
    else{
		echo '保存失败！'; 
	}
}

mysql_close();
?>